package com.apes.fn.server.workDesk.smartHelper.process;

import com.apes.framework.api.SpringManager;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: apes-server
 * @description:
 * @author: czs
 * @create: 2023-06-14 17:47
 **/
@Component
public class SmartHelperProcessFactory implements InitializingBean {

    private static List<SmartHelperProcess> smartHelperProcessList = null;
    private static List<CommonSmartDataProcess> commonSmartDataProcessList = null;
    private static Map<String,List<CommonSmartDataProcess>> commonSmartDataProcessLevelList = null;

    @Override
    public void afterPropertiesSet() {
        if (smartHelperProcessList == null) {
            smartHelperProcessList = new ArrayList<>();
            SpringManager.getApplicationContext().getBeansOfType(SmartHelperProcess.class);
            Map<String, SmartHelperProcess> beansOfType = SpringManager.getApplicationContext().getBeansOfType(SmartHelperProcess.class);
            beansOfType.forEach((key, value) -> smartHelperProcessList.add(value));

            commonSmartDataProcessList = smartHelperProcessList.stream()
                    .filter(smartHelperProcess -> smartHelperProcess instanceof CommonSmartDataProcess)
                    .map(s -> (CommonSmartDataProcess) s)
                    .filter(commonSmartDataProcess -> commonSmartDataProcess.support(""))
                    .distinct()
                    .collect(Collectors.toList());

            commonSmartDataProcessLevelList = commonSmartDataProcessList.stream().collect(Collectors.groupingBy(commonSmartDataProcess -> {
                List<String> levelList = commonSmartDataProcess.getLevelList();
                String lastName = levelList.get(levelList.size() - 2);
                return lastName+levelList.size();
            }));
        }
    }

    public static List<SmartHelperProcess> get() {

        return smartHelperProcessList;
    }
    public static List<CommonSmartDataProcess> getCommonSmartDataProcess() {

        return commonSmartDataProcessList;
    }
    public static List<CommonSmartDataProcess> getCommonSmartDataProcessNextLevel(CommonSmartDataProcess commonSmartDataProcess) {
        List<String> levelList = commonSmartDataProcess.getLevelList();
        String lastName = levelList.get(levelList.size() - 1);
        int size = levelList.size() + 1;
        return commonSmartDataProcessLevelList.getOrDefault(lastName + size,new ArrayList<>());
    }
}
